import storage from "@/utils/storage.js";
import config from '@/config/config';
import {
	acceptOrder,
	cancelOrder,
	orderPick,
	orderPicked,
	orderComplete,
	orderEvaluate,
	rePay,
	getOrderPayStatus
} from "@/api/order.js"
import {
	getPlatformInfo
} from "@/api/members.js"
let orderMixin = {
	data() {
		return {
			config,
			imgStyle: {
				border: {
					color: "#ccc",
					radius: "8"
				}
			},
			platformInfo: null,
			userInfo: {},
			orderItem: {},
			STATUS: {
				'pending': '待接单',
				'accepted': '已接单',
				'picked': '已取件',
				'delivered': '已送达',
				'completed': '已完成',
				'cancelled': '已取消',
			},
			pickupImages: [],
			pickedImages: [],
			commentForm: {
				comment: '',
				rating: 1,
				commentImages: []
			}
		}
	},
	created() {
		getPlatformInfo("commission_rate").then(res => {
			this.platformInfo = res.data.data.value || 10

		})
	},
	computed: {
		orderActionConfigs() {
			// 按需扩展按钮
			return [{
					text: '取消订单',
					show: item => this.isMyOrder(item) && ['pending', 'accepted'].includes(item.status),
				},
				{
					text: '私信',
					type: 'error',
					show: item => this.isMyOrder(item) && ['accepted', 'picked', 'delivered'].includes(item
						.status),
				},
				{
					text: '订单已完成',
					type: 'success',
					show: item => item.status === 'completed',
				},
				{
					text: '订单已取消',
					show: item => item.status === 'cancelled',
				},
				{
					text: '拍照取件',
					type: 'warning',
					show: item => this.isEmployee(item) && item.status === 'accepted',
				},
				{
					text: '拍照送达',
					type: 'success',
					show: item => this.isEmployee(item) && item.status === 'picked',
				},
				{
					text: '已送达,待确认',
					type: 'primary',
					show: item => this.isEmployee(item) && item.status === 'delivered',
				},
				{
					text: '配送中',
					type: 'warning',
					show: item => this.isEmployer(item) && ['accepted', 'picked'].includes(item.status),
				},
				{
					text: '确认完成',
					type: 'primary',
					show: item => this.isEmployer(item) && item.status === 'delivered',
				},
				{
					text: '已被接取',
					type: 'warning',
					show: item => !this.isMyOrder(item) && !['pending', 'cancelled'].includes(item.status),
				},
				{
					text: '立即抢单',
					type: 'error',
					show: item => !this.isMyOrder(item) && item.status === 'pending',
				},
				{
					text: '评价',
					type: 'warning',
					show: item => this.isEmployer(item) && item.status === 'completed' && !item.rating,
				},
				{
					text: '已评价',
					type: 'warning',
					show: item => item.status === 'completed' && item.rating,
				},
				{
					text: '去支付',
					type: 'warning',
					show: item => this.isEmployer(item) && item.status === 'pending' && item.payStatus ===
						'unpaid',
				},
			]
		}
	},
	methods: {
		// 判断是否是本人相关订单
		isMyOrder(item) {
			return this.isEmployer(item) || this.isEmployee(item);
		},
		isEmployer(item) {
			const userInfo = storage.getUserInfo();
			const userId = userInfo && userInfo._id;
			if (!userId || !item) return false;

			const requesterId = item.requester && item.requester._id;
			const requester = item.requester;

			return userId === requesterId || userId === requester;
		},
		isEmployee(item) {
			const userInfo = storage.getUserInfo();
			const userId = userInfo && userInfo._id;
			if (!userId || !item) return false;

			const accepterId = item.accepter && item.accepter._id;
			const accepter = item.accepter;

			return userId === accepterId || userId === accepter;
		},

		// 订单操作按钮点击
		clickEvent(item, text) {
			this.orderItem = item;
			switch (text) {
				case '立即抢单':
					this.grabOrders(item);
					break;
				case '拍照取件':
					this.takePhoto(item);
					break;
				case '拍照送达':
					this.pickedPhoto(item);
					break;
				case '确认完成':
					this.completeOrder(item);
					break;
				case '评价':
					this.clickScore(item);
					break;
				case '取消订单':
					this.cancelServiceOrder(item);
					break;
				case '私信':
					this.sendPrivateMsg(item);
					break;
				case '去支付':
					this.payServiceOrder(item);
					break;
				default:
					break;
			}
		},

		// 订单评价
		clickScore(item) {
			this.orderItem = item;
			if (this.openDialog && this.$refs.commonDialog) {
				this.openDialog({
					dialogType: 'score',
					title: '服务评价',
					confirmText: '提交',
					onConfirm: () => {
						this.confirmScore && this.confirmScore();
					}
				});
			} else if (this.$refs.popupScore) {
				this.$refs.popupScore.open();
			}
		},
		confirmScore() {
			this.commentForm.orderId = this.orderItem._id;
			orderEvaluate(this.commentForm).then(() => {
				uni.showToast({
					title: "评价成功",
					icon: "success"
				});
				this.refreshOrderList();
			});
		},

		// 抢单
		grabOrders(item) {
			const userInfo = storage.getUserInfo();
			if (userInfo.creditScore <= 60) {
				uni.showToast({
					title: "信誉分过低!",
					icon: "error"
				});
				return;
			}
			if (item.onlyOwner && !userInfo.isOwner) {
				this.openDialog({
					dialogType: 'owner',
					title: '仅限业主',
					content: '该订单仅限业主接单',
					confirmText: '前往认证',
					onConfirm: () => {
						this.$router.smartNavigate({
							url: '/pages/mePages/certifiedOwners'
						})
					}
				});
				return;
			}

			this.confirmGrabOrder && this.confirmGrabOrder(item);
		},

		// 取消订单
		cancelServiceOrder(item) {
			this.orderItem = item;
			this.confirmCancelOrder && this.confirmCancelOrder(this.orderItem);
		},
		confirmCancelOrder(item, reason = '') {
			cancelOrder({
				orderId: item._id,
				reason: reason
			}).then(res => {
				if (res.data.code === 200) {
					// 如果在订单详情页，刷新页面；否则跳转到订单详情页
					if (this.initInfo) {
						this.initInfo();
					} else {
						this.goPage(item);
					}
				}
			})
		},
		payServiceOrder(item) {
			const userInfo = storage.getUserInfo();
			rePay({
				orderId: item._id,
				openid: userInfo.openid
			}).then(res => {
				if (res.data.code === 200) {
					// 发起微信支付
					wx.requestPayment({
						...res.data.data.wxPayParams,
						success: () => {
							uni.showLoading({
								mask: true,
								title: "查询支付状态中...",
							})
							getOrderPayStatus({
								orderId: item._id
							}).then(res => {
								if (res.data.code === 200) {
									uni.hideLoading();
									// 如果在订单详情页，刷新页面；否则跳转到订单详情页
									if (this.initInfo) {
										this.initInfo();
									} else {
										uni.redirectTo({
											url: '/pages/homePages/orderInfo?id=' +
												item._id
										});
									}
								}
							})
							// uni.redirectTo({
							// 	url: '/pages/mePages/myService'
							// })
						},
						fail: (err) => {
					
							uni.hideLoading();
							uni.showToast({
								title: "支付失败",
								icon: "error"
							});
						}
					});
				}
			})
		},
		// 拍照取件
		takePhoto(item) {
			this.orderItem = item;
			if (item.type == '帮我买' && item.status == 'accepted') {
				// 弹窗输入金额和上传凭证
				this.openDialog({
					dialogType: 'actualInfo',
					title: '填写实际购买金额',
					onConfirm: () => {
						if (!this.amount) {
							uni.showToast({
								title: '请填写实际购买金额',
								icon: 'none'
							});
							return;
						}
						if (!this.imageList || !this.imageList.length) {
							uni.showToast({
								title: '请上传购物凭证',
								icon: 'none'
							});
							return;
						}
						orderPick({
							orderId: this.orderItem._id,
							actualAmount: this.amount,
							pickupVouchers: this.imageList
						}).then(() => {
							uni.showToast({
								title: '上传成功',
								icon: 'success'
							});
							this.refreshOrderList();
							this.amount = '';
							this.imageList = [];
						});
					}
				});
				return;
			}
			this.chooseAndUploadImage('pickupImages', orderPick, {
				orderId: item._id
			});
		},

		// 拍照送达
		pickedPhoto(item) {
			this.orderItem = item;
			this.chooseAndUploadImage('pickedImages', orderPicked, {
				orderId: item._id
			});
		},

		// 通用图片上传
		chooseAndUploadImage(imageArrKey, apiFunc, extraParams = {}) {
			uni.chooseImage({
				count: 1,
				sizeType: ['original', 'compressed'],
				sourceType: ['camera'],
				success: (res) => {
					const tempFilePath = res.tempFilePaths[0];
					this.uploadImage(tempFilePath, imageArrKey, apiFunc, extraParams);
				},
				fail: (err) => {
					console.error('拍照失败:', err);
				}
			});
		},
		uploadImage(filePath, imageArrKey, apiFunc, extraParams = {}) {
			const token = storage.getAccessToken();
			uni.uploadFile({
				url: `${config.commonApi}/api/upload/wechat-image`,
				filePath,
				name: 'file',
				header: {
					'authorization': token
				},
				success: (uploadFileRes) => {
					const data = JSON.parse(uploadFileRes.data);
					const imageData = {
						url: data.data.url
					};
					this[imageArrKey].push(imageData);

					if (typeof apiFunc === 'function') {
						const result = apiFunc({
							...extraParams,
							[imageArrKey]: this[imageArrKey]
						});
						if (result && typeof result.then === 'function') {
							result.then(() => {
								this.refreshOrderList && this.refreshOrderList();
							});
						} else {
							this.refreshOrderList && this.refreshOrderList();
						}
					} else {
						this.refreshOrderList && this.refreshOrderList();
					}
				}
			});
		},

		// 填写购买信息
		confirmActual(item, data) {
			// 添加调试信息
			

			if (!this.imageList?.length) {
				uni.showToast({
					title: "请上传凭证",
					icon: "error"
				});
				return;
			}
			if (!data || !data.amount) {
		
				uni.showToast({
					title: "请填写金额",
					icon: "error"
				});
				return;
			}
			orderPick({
				orderId: item._id,
				actualAmount: data.amount,
				pickupVouchers: this.imageList
			}).then(() => {
				this.refreshOrderList && this.refreshOrderList();
			});
		},

		// 确认完成
		completeOrder(item) {
			this.orderItem = item;
			if (item.type == '帮我买' && item.status == 'delivered') {
				this.openDialog({
					dialogType: 'buyComplete',
					title: '确认完成订单',
					confirmText: '去支付',
					data: item,
					onConfirm: () => {
						this.handlePayAndComplete && this.handlePayAndComplete(item);
					}
				});
				return;
			}
			this.openDialog({
				dialogType: 'receipt',
				title: '确认收货',
				content: '请确认已收到货物',
				onConfirm: () => {
					this.confirmReceipt && this.confirmReceipt();
				}
			});
		},
		handlePayAndComplete(item) {
			// 1. 调用支付接口
			const userInfo = storage.getUserInfo();

			orderComplete({
				orderId: this.orderItem._id,
				openid: userInfo.openid
			}).then((res) => {
				wx.requestPayment({
					...res.data.data,
					success: () => {
						uni.showLoading({
							mask: true,
							title: "查询支付状态中...",
						})

						getOrderPayStatus({
							outTradeNo: res.data.data.outTradeNo
						}).then(res => {
							uni.hideLoading();
							uni.redirectTo({
								url: '/pages/mePages/myService'
							})
						})


					},
					fail: (err) => {
						uni.showToast({
							title: '支付失败',
							icon: 'none'
						});
					}
				});
			});

		},
		confirmReceipt() {
			orderComplete({
				orderId: this.orderItem._id
			}).then(res => {
				if (res.data.code === 200) this.refreshOrderList();
			});
		},

		// 跳转详情
		goPage(item) {
			if (!item) {
				console.error('item is null or undefined');
				uni.showToast({
					title: '订单信息异常',
					icon: 'error'
				});
				return;
			}

			const userInfo = storage.getUserInfo();

			// 权限控制：只有下单人或接单人才能查看订单详情
			// 1. 如果是我的订单（下单人或接单人），允许查看
			// 2. 如果不是我的订单，且订单已被接取（状态不是pending），则不允许查看
			if (!this.isMyOrder(item)) {
				// 不是我的订单，检查订单状态
				if (item.status !== 'pending') {
					// 订单已被接取，不允许查看
					uni.showToast({
						title: "订单已被接取，无法查看详情",
						icon: "error"
					});
					return;
				}
			}

			// 业主权限检查
			if (item.onlyOwner && !userInfo.isOwner && !this.isEmployer(item)) {
				// 使用通用弹窗显示业主权限提示
				this.openDialog({
					dialogType: 'owner',
					title: '仅限业主',
					content: '该订单仅限业主接单',
					confirmText: '前往认证',
					onConfirm: () => {
						this.$router.smartNavigate({
							url: '/pages/mePages/certifiedOwners'
						});
					}
				});
				return;
			}

			// 通过权限检查，允许查看订单详情
			const url = `/pages/homePages/orderInfo?id=${item._id}`;
			this.$router.smartNavigate({
				url: url
			});
		},

		// 上传凭证
		voucherUploadImages(e) {
			this.uploadImage(e.tempFilePaths[0], 'imageList', () => {}, {});
		},
		// 上传评价图片
		commentUploadImages(e) {
			this.uploadImage(e.tempFilePaths[0], 'commentForm.commentImages', () => {}, {});
		},

		// 私信
		sendPrivateMsg(item) {
			// 数据验证
			if (!item) {
				uni.showToast({
					title: '订单信息不完整',
					icon: 'error'
				});
				return;
			}

			let msgObj = this.isEmployer(item) ? item.accepter : item.requester;

			// 验证聊天对象信息
			if (!msgObj) {
				uni.showToast({
					title: '暂无法获取聊天对象信息',
					icon: 'error'
				});
				return;
			}

			if (!msgObj._id) {
				uni.showToast({
					title: '聊天对象ID缺失',
					icon: 'error'
				});
				return;
			}

			if (!msgObj.nickname) {
				uni.showToast({
					title: '聊天对象昵称缺失',
					icon: 'error'
				});
				return;
			}

			// 跳转到聊天页面
	
			this.$router.smartNavigate({
				url: `/pages/homePages/messageInfo?name=${msgObj.nickname}&avatar=${encodeURIComponent(msgObj.avatar || '')}&userId=${msgObj._id}`
			});
		},

		// 刷新订单列表
		refreshOrderList() {
			this.$emit('updataList');
			this.initInfo && this.initInfo();
		},

		// 工具方法
		setTypeText(statusObj, type) {
			return statusObj[type];
		},
		displayFee(item) {
			// 假设平台抽成字段叫 commissionRatio
			const commissionRatio = this.platformInfo / 100;
			const reward = parseFloat(item.reward) || 0;
			let finalFee = this.isEmployer(item) ? reward : reward * (1 - commissionRatio);
			return finalFee.toFixed(2); // 保留两位小数
		},
		formatDate(dateString) {
			if (!dateString) return '';
			const date = new Date(dateString),
				now = new Date();
			const diff = Math.floor((now - date) / 1000);
			if (diff < 60) return '刚刚';
			if (diff < 3600) return `${Math.floor(diff / 60)}分钟前`;
			if (date.toDateString() === now.toDateString())
				return `${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
			if (date.getFullYear() === now.getFullYear())
				return `${date.getMonth() + 1}月${date.getDate()}日`;
			return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
		},
		formatTime(utcTimeString) {
			if (!utcTimeString) return false;
			const now = new Date(),
				inputDate = new Date(utcTimeString);
			const nowDate = now.getDate(),
				inputDateDate = inputDate.getDate();
			let dayLabel = "";
			if (nowDate === inputDateDate) dayLabel = "今天";
			else if (nowDate + 1 === inputDateDate) dayLabel = "明天";
			const weekdays = ["日", "一", "二", "三", "四", "五", "六"];
			const weekday = `周${weekdays[inputDate.getDay()]}`;
			const hours = inputDate.getHours().toString().padStart(2, '0');
			const minutes = inputDate.getMinutes().toString().padStart(2, '0');
			const time = `${hours}:${minutes}`;
			return dayLabel ? `${dayLabel}${weekday} ${time}` : `${weekday} ${time}`;
		},
		// 确认抢单
		confirmGrabOrder(item) {
			acceptOrder(item._id).then(res => {
				if (res.data && res.data.code === 200) {
					uni.showToast({
						title: '抢单成功',
						icon: 'success'
					});
					this.$router.smartNavigate({
						url: `/pages/homePages/orderInfo?id=${item._id}`
					});
				} else {
					uni.showToast({
						title: res.data?.message || '抢单失败',
						icon: 'none'
					});
				}
			});
		}
	}
}

export default orderMixin;